package com.longma.server.util;

import com.longma.server.constant.enums.ResponseCode;
import com.longma.server.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 *  @Author: zy
 *  @Date: 2020/4/15 22:37
 *  @Description: 请求上下文
 */
@Slf4j
public final class AuthContextUtil {

    /**
     * 禁止实例化
     */
    private AuthContextUtil() {
        throw new AssertionError();
    }

    /**
     * 在项目的任意位置获取当前Request
     */
    public static HttpServletRequest getCurrentRequest() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attrs == null) {
            throw new BusinessException(ResponseCode.PARAM_NOT_COMPLETE);
        }
        return attrs.getRequest();
    }


    /**
     * 获取当前登录用户
     */
    public static String getLoginName() {
        //获取当前登录用户
        User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (user != null) {
            return user.getUsername();
        } else {
            throw new BusinessException(ResponseCode.NO_PERMISSION);
        }
    }
}
